Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Socket io, Try multiple URLs to establish connection after "connect_error"

I have an app with divided code (client / server). On the client side, I'd like socket io to attempt multiple URLs (one at a time) until it connects successfully.

Here's my code:

const BAD_HOST = "http://localhost:8081";
const LOCAL_HOST = "http://localhost:8080";
const SOCKET_CONFIG = {
  upgrade: false,
  transports: ["websocket"],
  auth: { ... }, // Trimmed for brevity
  extraHeaders: { ... }, // Trimmed for brevity
};

let socket = io(BAD_HOST, SOCKET_CONFIG); // This connects fine when I use LOCAL_HOST

socket.on("connect_error", (err) => {
  console.log(err); 
  socket = io(LOCAL_HOST, SOCKET_CONFIG); // DOES NOT WORK
});

socket.on("connect", () => { ... } // Trimmed for brevity

In short, when I try to reassign the value for socket to a new io connection, it seems to retain the old, failed connection. My browser continues to throw 'connect_error' messages from the bad url: WebSocket connection to 'ws://localhost:8081/socket.io/?EIO=4&transport=websocket' failed:

I checked but couldn't find any official documentation on this question.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think an approach is already discussed here: https://stackoverflow.com/a/22722710/656708

Essentially you have an array of URLs, which in your case would be:

const socketServerURLs = ["http://localhost:8081","http://localhost:8080"];

and then iterate over them, trying to initiate a socket connection, like this:

// something along these lines
socketServerURLs.forEach((url) => { 
  // ...
  socket.connect(url, socketConfiguration, (client) => {});
  // ...
}

Then again, I don't know what a BAD_HOST entails. Assuming that you mean that a connection to that host failed, how would you know that without actually trying to connect to it?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda